package com.finalist.controller.travel.weixin;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.Setting;
import com.finalist.controller.shop.BaseController;
import com.finalist.entity.Member;
import com.finalist.entity.Member.MaritalStatus;
import com.finalist.interceptor.WeixinInterceptor;
import com.finalist.plugin.StoragePlugin;
import com.finalist.service.MemberService;
import com.finalist.service.OrderService;
import com.finalist.util.FreemarkerUtils;
import com.finalist.util.ImageUtils;
import com.finalist.util.SettingUtils;

@Controller("travelWeixinUserController")
@RequestMapping("/travel/weixin/user")
public class UserController  extends BaseController{
	
	protected static final String VIEW = "/travel/weixin/user/";
	
	@Resource(name = "memberServiceImpl")
	private  MemberService memberService;
	
	@Resource(name = "orderServiceImpl")
	private OrderService orderService;
	
	@Resource
	private List<StoragePlugin> storagePlugins;
	
	/** 目标扩展名 */
	private static final String DEST_EXTENSION = "jpg";
	/** 目标文件类型 */
	private static final String DEST_CONTENT_TYPE = "image/jpeg";
	
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request, ModelMap model){
		Member member = (Member)request.getAttribute("currentUser");
		if(member==null){
			member = memberService.findByUnionId("1");
		}
		model.put("user", member);
		//在查询之前，先处理未支付切超过45分钟的订单
		orderService.updateOrderNopaid();
		//未支付
		model.put("unPaidOrder", orderService.findPage(member,1));
		//已支付
		model.put("paidOrder", orderService.findPage(member,2));
		//进行中
		model.put("ongoingOrder", orderService.findPage(member,3));
		//已完成
		model.put("completedOrder", orderService.findPage(member,4));
		//已关闭
		model.put("cancellOrder", orderService.findPage(member,5));
		return VIEW + "index";
	}
	
	@RequestMapping("/edit")
	public String edit(HttpServletRequest request, ModelMap model){
		Member member = (Member)request.getAttribute("currentUser");
		if(member==null){
			member = memberService.findByUnionId("1");
		}
		model.put("user", member);
		return VIEW + "updateUser";
	}
	
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	public String update(Member member,MultipartFile file,HttpServletRequest request, RedirectAttributes redirectAttributes,
			ModelMap model){
		String imageUrl = saveMemberImage(file);
		Member persistent = memberService.findByUnionId(member.getUnionId());
		persistent.setUsername(member.getUsername());
		if(StringUtils.isNotBlank(imageUrl)){
			persistent.setHeadImgUrl(imageUrl);
		}
		persistent.setMobile(member.getMobile());
		persistent.setMemo(member.getMemo());
		persistent.setGender(member.getGender());
		
		persistent.setMaritalStatus(member.getMaritalStatus());
		persistent.setIndustry(member.getIndustry());
		persistent.setSchool(member.getSchool());
		persistent.setHometown(member.getHometown());
		persistent.setHobby(member.getHobby());
		
		memberService.update(persistent);
		model.put("user", persistent);
		//未支付
		model.put("unPaidOrder", orderService.findPage(persistent,1));
		//已支付
		model.put("paidOrder", orderService.findPage(persistent,2));
		//进行中
		model.put("ongoingOrder", orderService.findPage(persistent,3));
		//已完成
		model.put("completedOrder", orderService.findPage(persistent,4));
		//已关闭
		model.put("cancellOrder", orderService.findPage(persistent,5));
		return VIEW+"index";
	}
	
	
	public String saveMemberImage(MultipartFile file){

		MultipartFile multipartFile = file;
		if (multipartFile != null && !multipartFile.isEmpty()) {
			try {
				Setting setting = SettingUtils.get();
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("uuid", UUID.randomUUID().toString());
				String uploadPath = FreemarkerUtils.process(setting.getImageUploadPath(), model);
				String uuid = UUID.randomUUID().toString();
				//原始图片上传路径
				String sourcePath = uploadPath + uuid + "-source." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
				//缩略图片上传路径
				String thumbnailPath = uploadPath + uuid + "-thumbnail." + DEST_EXTENSION;
				Collections.sort(storagePlugins);
				for (StoragePlugin storagePlugin : storagePlugins) {
					if (storagePlugin.getIsEnabled()) {
						File tempFile = new File("/home/img" + "/upload_" + UUID.randomUUID() + ".jpg");
						if (!tempFile.getParentFile().exists()) {
							tempFile.getParentFile().mkdirs();
						}
						multipartFile.transferTo(tempFile);
						Collections.sort(storagePlugins);
						for (StoragePlugin _storagePlugin : storagePlugins) {
							if (_storagePlugin.getIsEnabled()) {
								try {
									File thumbnailTempFile = new File("/home/img" + "/upload_" + UUID.randomUUID() + "." + DEST_EXTENSION);
									ImageUtils.zoom(tempFile, thumbnailTempFile, 60, 60);
									storagePlugin.upload(sourcePath, tempFile, file.getContentType());
									storagePlugin.upload(thumbnailPath, thumbnailTempFile, DEST_CONTENT_TYPE);
								} finally {
									FileUtils.deleteQuietly(tempFile);
								}
								break;
							}
						}
						return storagePlugin.getUrl(thumbnailPath);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
